package services

import (
	."ircove.com/common"
	."ircove.com/irc"
	"ircove.com/repository"
	"fmt"
	"strings"
	"crypto/md5"
	"strconv"
)


func Reg()  {
	RegisterCommand(10,UserAuthByToken)
	RegisterCommand(11,Subscribe)
	RegisterCommand(12,PushMessage)
	RegisterCommand(13,PushChannelMessage)
}
//Token验证
func UserAuthByToken(context *VFContext) *VFResult {
	deviceid:=context.Args["deviceid"]
	if len(deviceid)==0 {
		return NewVFResult_VFcode(ErrorArgument.Clone("deviceid is null"))
	}
	appid :=context.Args["appid"]
	if len(appid)==0 {
		return NewVFResult_VFcode(ErrorArgument.Clone("appid is null"))
	}
	sign :=context.Args["sign"]
	if len(sign)==0 {
		return NewVFResult_VFcode(ErrorArgument.Clone("sign is null"))
	}
	sign=strings.ToLower(sign)
	vtoken:=context.Args["vtoken"]
	timespan:=context.Args["timespan"]
	if len(timespan)==0 {
		return NewVFResult_VFcode(ErrorArgument.Clone("timespan is null"))
	}
	version:=context.Args["version"]
	if len(version)==0 {
		return NewVFResult_VFcode(ErrorArgument.Clone("timespan is null"))
	}
    app,err:= repository.App_Find(appid)
	if err !=nil || appid !=app.AppName {
		return NewVFResult_VFcode(ObjecctNotFound.Clone("appid is error"))
	}
	token:=app.AppKey
	text := appid + timespan+ deviceid + version + token
	Invalid:= fmt.Sprintf("%x", md5.Sum([]byte(text))) //将[]byte转成16进制
	if Invalid !=sign {
		return NewVFResult_VFcode(InvalidSignature.Clone("sign is error"))
	}
    session:=new(Session)
    session.AppId=app.Id
    session.DeviceId=deviceid
	if len(vtoken)>0 {
		userid,err:= TokenDecode(deviceid,vtoken)
		if err !=nil {
			return NewVFResult_VFcode(ErrorArgument.Clone(err.Error()))
		}
		if userid>0 {
			session.UserIsAuth=true
			session.AuthType="vtoken"
			session.UserID=int64(userid)
		}
	}

	context.Client.DeviceToken=strconv.Itoa(session.AppId) + "|" + deviceid
	context.Client.Session=session

	////重复登陆
	//c:= context.Client.Server.Clients[context.Client.Id]
	//if c!=nil && c.Id!=context.Client.Id {
     //   c.Closechain <-1
	//}
	context.Client.Server.Clients[context.Client.DeviceToken]=context.Client
	redis_userAuth(context)
	return NewVFResult("ok")
}